package com.imot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.imot.handler.ImotExciption;
import com.imot.mapper.EmaErrorRecordMapper;
import com.imot.mapper.EmaExceptionRecordMapper;
import com.imot.pojo.entity.EmaErrorRecord;
import com.imot.pojo.enums.DateEnum;
import com.imot.pojo.vo.FaultDetailsVo;
import com.imot.response.Result;
import com.imot.service.HealthStatusService;
import com.imot.service.IEmaErrorRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * ClassName: HealthStatusServiceImpl
 * Description:
 * date: 2023/11/29 16:39
 *
 * @author imot-jiah.wang
 */
@Service
@RequiredArgsConstructor
public class HealthStatusServiceImpl implements HealthStatusService {
    private final IEmaErrorRecordService emaErrorRecordService;

    private final EmaErrorRecordMapper emaErrorRecordMapper;

    @Override
    public Result getDowntime() {

        return Result.success();
    }

    @Override
    public Result getDeviceDetails() {
        return Result.success();
    }

    @Override
    public Result getFailurePrediction() {
        return null;
    }

    @Override
    public Result getFaultTypeDistribution(String date) {
        DateEnum dateEnum = Enum.valueOf(DateEnum.class,date.toUpperCase());

        LocalDate end = LocalDate.now();
        LocalDate start = null;
        if (dateEnum.equals(DateEnum.YEAR)){
            start = end.withDayOfMonth(1);
        }
        if (dateEnum.equals(DateEnum.QUARTER)){
            start = end.withDayOfYear(1);
        }
        if (dateEnum.equals(DateEnum.MONTH)){
            int currentMonth = end.getMonthValue();
            int startMonthOfQuarter = ((currentMonth - 1) / 3) * 3 + 1;
            start = end.withMonth(startMonthOfQuarter).withDayOfMonth(1);
        }
        if (start == null)throw new ImotExciption(500,"传入参数有误");
        Map<String, Integer> theLecel = emaErrorRecordMapper.getTheLecel(start, end);

        return Result.success(theLecel);
    }

    @Override
    public Result getFaultDetails() {
        LambdaQueryWrapper<EmaErrorRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(EmaErrorRecord::getId);
        wrapper.last("limit 50");
        List<EmaErrorRecord> list = emaErrorRecordService.list(wrapper);
        ArrayList<FaultDetailsVo> faultDetailsVos = new ArrayList<>();
        for (EmaErrorRecord emaErrorRecord : list) {
            FaultDetailsVo faultDetailsVo = new FaultDetailsVo();
            BeanUtils.copyProperties(emaErrorRecord,faultDetailsVo);
            faultDetailsVos.add(faultDetailsVo);
        }

        return Result.success(faultDetailsVos);
    }

    @Override
    public Result getEnergyConsumptionStats() {
        return null;
    }
}

